package com.miao.util.db;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author created by Miaosk
 * @date created on 2015/5/12 14:45.
 */
public class DBUtils {
    private static DataSource dataSource = null;

    static {
        Properties p = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config/db/druid.properties");
            p.load(inputStream);
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Connection getConn()
            throws SQLException {
        return dataSource.getConnection();
    }

    public static void main(String[] args) {
        try {
            Connection conn = dataSource.getConnection();
            ResultSet rs = conn.createStatement().executeQuery("select now()");
            while (rs.next())
                System.out.println(rs.getString(1));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void free(ResultSet rs, Statement st, Connection conn) throws SQLException {
        if (rs != null) rs.close();
        if (st != null) st.close();
        if (conn != null) conn.close();
    }
}
